import 'dart:convert';

import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:safetymonitor/app/components/data_table.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/data/entities/home/monitor/person_monitoring_page_entity_entity.dart';
import 'package:safetymonitor/router/app_pages.dart';

final class NewPersonnelMonitoringPage extends StatefulWidget {
  const NewPersonnelMonitoringPage({super.key});

  @override
  State<NewPersonnelMonitoringPage> createState() => _NewPersonnelMonitoringPageState();
}

class _NewPersonnelMonitoringPageState extends State<NewPersonnelMonitoringPage> with AutomaticKeepAliveClientMixin {
  final List<List<String>> tableData = [];
  URLRequest? url;
  InAppWebViewController? inAppWebViewController;

  @override
  void initState() {
    url = URLRequest(url: WebUri('${Interface.plotMapAddress}/#/nest?func=3dDisplay&_t=1712826013832'));
    personMonitoring();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SingleChildScrollView(
      physics: const ClampingScrollPhysics(),
      child: Container(
        padding: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 20.w),
        color: Colors.white,
        child: Column(
          children: [
            AppGaps.vGap30,
            SizedBox(
              height: tableData.length == 1 ? 50.w : 200.w,
              child: DataTables(
                tableData,
                onActionClick: (String row) {
                  Get.toNamed(Routes.dynamicTrajectoryPage, arguments: tableData[int.parse(row)]);
                },
              ),
            ),
            // AppGaps.vGap20,
            const Divider(color: Color(0xffE2E8FD)),
            AppGaps.vGap16,
            Row(
              children: [
                SvgPicture.asset('assets/svg/new_safe_personnel_xing.svg'),
                AppGaps.hGap10,
                Text(
                  '动态轨迹',
                  style: TextStyle(
                    color: const Color(0xFF1D3452),
                    fontWeight: FontWeight.w500,
                    fontSize: 16.sp,
                  ),
                )
              ],
            ),
            AppGaps.vGap30,
            SizedBox(
              height: 180.w,
              child: InAppWebView(
                initialUrlRequest: url,
                onWebViewCreated: onWebViewCreated,
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///获得人员实时监测分页
  void personMonitoring() async {
    tableData.clear();
    tableData.add(['人员单位', '人员姓名', '人员分组', '人员工种', '进场时间', '出场时间']);
    final res = await HttpUtil().generateGetRequest<List<PersonMonitoringPageEntityEntity>>(
      Interface.realtimePersonMonitoring,
      queryParameters: {
        // 'enterTime': ['2022-12-08 00:00:00', '2024-12-08 00:00:00'],
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        final List<PersonMonitoringPageEntityEntity> tableDataS = result.data ?? [];
        for (PersonMonitoringPageEntityEntity data in tableDataS) {
          final List<String> sub = [
            data.companyName ?? '',
            data.name ?? '',
            '${data.groupId ?? ''}',
            '${data.craft ?? ''}',
            data.enterTime ?? '',
            data.exitTime ?? '',
          ];
          tableData.add(sub);
        }
      }
    });
    setState(() {});
  }

  /// 发送消息
  Future<void> _sendMessage(data) async {
    print('_sendMessage：${jsonEncode(data)}');
    await inAppWebViewController?.postWebMessage(message: WebMessage(data: jsonEncode(data)));
  }

  /// webview加载完成后
  onWebViewCreated(InAppWebViewController controller) async {
    inAppWebViewController = controller;
    // 先加载地形
    await _loadTerrain('http://203.25.217.225:38080/model/SCDiXing/yibin');
    // 加载瓦片
    await _loadTileset('http://203.25.217.39:81/model/SiChuan/YiBin/P-YB003/tileset.json');
    // 数据初始化
    await _postData();
    //元素定位
    await _dataFlyTo();
  }

  // 加载地形地址
  _loadTerrain(String url) async {
    final data = {
      'type': 'Terrain',
      'data': {
        'url': url,
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  /// 加载瓦片地址
  _loadTileset(String tilesetUrl) async {
    final data = {
      'type': 'Tileset',
      'data': {
        'url': tilesetUrl,
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  /// 数据初始化
  _postData() async {
    final data = {
      'type': 'DataInit',
      'data': {
        'group': 'default',
        'data': [
          {
            'UIMode': '',
            'configs': {
              'width': 5,
              'ground': false,
              'color': [0, 0, 1, 1]
            },
            'id': 'bbcd1238-aacc-3652-56ad-205ccfe25ad36df1',
            'mode': 'Line',
            'name': '折线',
            'options': {},
            'positions': [
              [1.8530639859151827, 0.5622286129483111, 446.5617771720005],
              [1.8531749571298854, 0.5621935754044496, 437.157911543327],
              [1.8532849199495545, 0.5621500160266254, 440.7667009817055],
              [1.8533606669542368, 0.5621172083031845, 418.5505116020397],
              [1.8533287330627952, 0.5622009648876174, 417.5998763424102],
              [1.8532815415406612, 0.562213362845909, 417.85899726780985],
              [1.8532297574101988, 0.5622139724445525, 418.00557163438214],
              [1.853183387732425, 0.562210601397865, 419.79313711032836],
              [1.8531650073398975, 0.5622368444783143, 419.7270150899306],
              [1.8531478188792019, 0.562284372899488, 420.9522419467134],
              [1.8531240989156792, 0.5622906481020712, 421.9035484607923],
              [1.8530945622531374, 0.5622812676995226, 422.80063817963423],
              [1.8530582387895447, 0.5622669232860149, 430.22750521319284],
              [1.8530157701889423, 0.5622596479982619, 428.4668716538621],
              [1.852972665153191, 0.5622570330130235, 427.77806307353836]
            ],
            'type': 'GeoPolyline'
          },
        ]
      }
    };
    await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  /// 元素定位
  _dataFlyTo() async {
    final data = {
      'type': 'DataFlyTo',
      'data': {
        'key': 'bbcd1238-aacc-3652-56ad-205ccfe25ad36df1',
      }
    };
    // await Future.delayed(const Duration(seconds: 2));
    _sendMessage(data);
  }

  @override
  void dispose() {
    inAppWebViewController?.dispose();
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;
}
